package com.mercadoutils.controller;


import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mercadolibre.sdk.Meli;
import com.mercadolibre.sdk.MeliException;
import com.mercadoutils.listeners.SesionListener;
import com.mercadoutils.singletons.PoolConectionsSingleton;
import com.ning.http.client.FluentStringsMap;
import com.ning.http.client.Response;
 
@Controller
public class HomeController{
    protected final Logger logger = Logger.getLogger(getClass());
    
    @RequestMapping("/home.html")
    public String handleRequest(Model model) throws MeliException, IOException, ServletException, SQLException {
 
        logger.debug("Returning index view");
        HttpSession session = SesionListener.getSession();
        Meli m = (Meli) session.getAttribute("meli");
        
        //category
		Response r = m.get("/categories/MLA1648");
		String resultado = r.getResponseBody().toString();
		model.addAttribute("message", resultado);
		
		//publicados
		 FluentStringsMap params = new FluentStringsMap();
        params.add("access_token", m.getAccessToken());
        r = m.get("/users/me",params);
		resultado = r.getResponseBody().toString(); 
		JsonElement jelement = new JsonParser().parse(resultado); 
	    JsonObject  jobject = jelement.getAsJsonObject();
	    
	    params.clear();
	    params.add("seller_id", jobject.get("id").toString());
	    
	    r = m.get("/sites/MLA/search",params);
	    
	    
	    resultado = r.getResponseBody().toString();
	    jelement = new JsonParser().parse(resultado); 
	    jobject = jelement.getAsJsonObject();
	    JsonArray jsonResults = jobject.getAsJsonArray("results");
	    model.addAttribute("publicados", jsonResults.size());

	    //stock
	    int sumador = 0;
	    for(int i=0;i<jsonResults.size();i++){
	    	if(Integer.parseInt(jsonResults.get(i).getAsJsonObject().get("available_quantity").toString())<=0)
	    		sumador++;
	    }
	    model.addAttribute("stock", sumador);
//	    
	    //pendientes
	    Connection conexion = PoolConectionsSingleton.getConection();  	
		Statement st = conexion.createStatement();
		ResultSet rs = st.executeQuery("select count(*) as cantidad  from item where status = 'eter'");
        
	    int result = 0;
	    while(rs.next()){
	    	result=rs.getInt("cantidad");
	    }
	    model.addAttribute("pendientes", result);
	    
	    //preguntas
	    params.clear();
	    params.add("status", "unanswered");
        params.add("access_token", m.getAccessToken());
        r = m.get("/my/received_questions/search",params);
       
		resultado = r.getResponseBody().toString(); 
		jelement = new JsonParser().parse(resultado); 
	    jobject = jelement.getAsJsonObject();
	    
	    JsonArray jarray = jobject.getAsJsonArray("questions");
	    model.addAttribute("mensajes", jarray.size());
	    
	    
//		System.out.println(resultado);
//		JsonElement jelement = new JsonParser().parse(resultado); 
//	    JsonObject  jobject = jelement.getAsJsonObject();
//	    JsonArray jarray = jobject.getAsJsonArray("categories");
//	    jobject = jarray.get(0).getAsJsonObject();
		
		
		
		model.addAttribute("nombre",session.getAttribute("nombre"));
		model.addAttribute("apellido",session.getAttribute("apellido"));
		model.addAttribute("role",session.getAttribute("role"));
		model.addAttribute("srcImagen","http://localhost:8080/MercadoUtils/imagenesDB/"+session.getAttribute("srcImagen"));
        return "home";
    }
}